package com.wzbc.video.controller;

import com.alibaba.druid.sql.visitor.functions.Concat;
import com.wzbc.video.api.CommonResult;
import com.wzbc.video.req.ChapterIdReq;
import com.wzbc.video.req.IdReq;
import com.wzbc.video.req.StringReq;
import com.wzbc.video.service.FileService;
import com.wzbc.video.utils.TokenUtil;
import com.wzbc.video.entity.File;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

import static com.wzbc.video.utils.FileUtil.download;
import static com.wzbc.video.utils.FileUtil.saveFile;

@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private TokenUtil tokenUtil;

    @Autowired
    private FileService fileService;

    @PostMapping("/saveVideo")
    public CommonResult upload(MultipartFile file, HttpServletRequest req) {
        String id = tokenUtil.getToken(req.getHeader("X-Token"));
        String url = saveFile(file, "video", id);
        if (url.equals("empty") || url.equals("bad")) {
            return CommonResult.failed(url);
        }
        return CommonResult.success(url);
    }

    @PostMapping("/download")
    public CommonResult download1(@RequestBody StringReq req, HttpServletResponse response) {
        String path = req.getName();
        java.io.File file = new java.io.File(path);
        if (file.exists()) {
            System.out.println("路径存在");
            return CommonResult.success(download(path, response));
        }
        return CommonResult.failed("下载失败");
    }

    @PostMapping("/getChapterFile")
    public CommonResult getChapterFile(@RequestBody IdReq req) {
        if (req.getId() == 0L) {
            return CommonResult.failed("没有id为0的章节");
        }
        return CommonResult.success(fileService.getFile(req.getId()));
    }

    @PostMapping("/delete")
    public CommonResult deleteChapter(@RequestBody IdReq req) {
        return CommonResult.success(fileService.deleteById(req.getId()));
    }

    @PostMapping("/insert")
    public CommonResult insert(@RequestBody File file, HttpServletRequest req) {
        file.setUploadId(Long.parseLong(tokenUtil.getToken(req.getHeader("X-Token"))));
        Integer num = fileService.insert(file);
        if (num == -1) {
            return CommonResult.failed("请先删除相同文件");
        }
        return CommonResult.success(num);
    }

}
